/*
 * SADFinanceiroView.java
 */

package sadfinanceiro;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;
import org.jdesktop.application.Action;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.ui.RefineryUtilities;
import sadfinanceiro.calculos.Calculador;
import sadfinanceiro.model.Investimento;

/**
 * The application's main frame.
 */
public class SADFinanceiroView extends FrameView {

    DecimalFormat df = new DecimalFormat("#,##0.00");
    
    public SADFinanceiroView(SingleFrameApplication app) {
        super(app);
        initComponents();
   }

    @Action
    public void showIndicesPoupanca() {
        showIndices(1);
    }

    @Action
    public void showIndicesCDB() {
        showIndices(2);
    }

    private void showIndices(int tipo) {
        JFrame mainFrame = SADFinanceiroApp.getApplication().getMainFrame();
        indicesView = new SADFinanceiroIndicesView(mainFrame,true,tipo);
        indicesView.pack();
        RefineryUtilities.centerFrameOnScreen(indicesView);
        indicesView.setVisible(true);
    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = SADFinanceiroApp.getApplication().getMainFrame();
            aboutBox = new SADFinanceiroAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        SADFinanceiroApp.getApplication().show(aboutBox);
    }

    @Action
    public void showHistoricoBox() {
        JFrame mainFrame = SADFinanceiroApp.getApplication().getMainFrame();
        historicoView = new SADFinanceiroHistoricoView(mainFrame, true);
        historicoView.pack();
        RefineryUtilities.centerFrameOnScreen(historicoView);
        historicoView.setVisible(true);
    }

    @Action
    public void limparHistorico() {
        try {
            EntityTransaction et = entityManager.getTransaction();
            et.begin();
            Query delete = entityManager.createNativeQuery("DELETE FROM APP.CENARIOS");
            int numRows = delete.executeUpdate();
            int optionSelected = JOptionPane.showConfirmDialog(jDesktopPane1, "Serão apagados todos os cenários já gerados totalizando "+numRows+" registros.", "", JOptionPane.YES_NO_OPTION);
            if (optionSelected==0) { //sim
                JOptionPane.showMessageDialog(jDesktopPane1, "Registros Apagados");
                et.commit();

                DefaultTableModel modeloTabela = (DefaultTableModel)tabela.getModel();
                for (int i = 0; i < modeloTabela.getRowCount(); i++) {
                    modeloTabela.removeRow(i);
                }

            }else {
                et.rollback();
            }
        }catch(Exception e) {
            JOptionPane.showMessageDialog(jDesktopPane1, "Erro: "+e.getMessage());
            e.printStackTrace();
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jDesktopPane1 = new javax.swing.JDesktopPane();
        jLabel2 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        valorReforcos = new javax.swing.JFormattedTextField();
        valorFuturo = new javax.swing.JFormattedTextField();
        jButton1 = new javax.swing.JButton();
        jLabel7 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        rentabilidade = new javax.swing.JFormattedTextField();
        tempoAplicacao = new javax.swing.JFormattedTextField();
        capitalInicial = new javax.swing.JFormattedTextField();
        jButton2 = new javax.swing.JButton();
        jDesktopPane2 = new javax.swing.JDesktopPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabela = new javax.swing.JTable();
        jButton3 = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        pesoValorFuturo = new javax.swing.JComboBox();
        pesoCapitalInicial = new javax.swing.JComboBox();
        pesoRentabilidade = new javax.swing.JComboBox();
        pesoPrazo = new javax.swing.JComboBox();
        pesoReforcoMensal = new javax.swing.JComboBox();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        indicesMenu = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenuItem2 = new javax.swing.JMenuItem();
        jMenuItem3 = new javax.swing.JMenuItem();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem4 = new javax.swing.JMenuItem();
        jMenuItem5 = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        entityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("sadfinanceiroPU").createEntityManager();

        mainPanel.setName("mainPanel"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(sadfinanceiro.SADFinanceiroApp.class).getContext().getResourceMap(SADFinanceiroView.class);
        jTabbedPane1.setBackground(resourceMap.getColor("jTabbedPane1.background")); // NOI18N
        jTabbedPane1.setForeground(resourceMap.getColor("jTabbedPane1.foreground")); // NOI18N
        jTabbedPane1.setName("jTabbedPane1"); // NOI18N

        jDesktopPane1.setBackground(resourceMap.getColor("jDesktopPane1.background")); // NOI18N
        jDesktopPane1.setName("jDesktopPane1"); // NOI18N

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N
        jLabel2.setBounds(0, 10, 130, 17);
        jDesktopPane1.add(jLabel2, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N
        jLabel1.setBounds(0, 40, 120, 17);
        jDesktopPane1.add(jLabel1, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N
        jLabel3.setBounds(0, 70, 110, 17);
        jDesktopPane1.add(jLabel3, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N
        jLabel4.setBounds(0, 100, 140, 17);
        jDesktopPane1.add(jLabel4, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jLabel6.setText(resourceMap.getString("jLabel6.text")); // NOI18N
        jLabel6.setName("jLabel6"); // NOI18N
        jLabel6.setBounds(0, 130, 130, 17);
        jDesktopPane1.add(jLabel6, javax.swing.JLayeredPane.DEFAULT_LAYER);

        valorReforcos.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#,##0.00"))));
        valorReforcos.setText(resourceMap.getString("valorReforcos.text")); // NOI18N
        valorReforcos.setName("valorReforcos"); // NOI18N
        valorReforcos.setBounds(150, 100, 60, 27);
        jDesktopPane1.add(valorReforcos, javax.swing.JLayeredPane.DEFAULT_LAYER);

        valorFuturo.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#,##0.00"))));
        valorFuturo.setText(resourceMap.getString("valorFuturo.text")); // NOI18N
        valorFuturo.setName("valorFuturo"); // NOI18N
        valorFuturo.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                valorFuturoFocusLost(evt);
            }
        });
        valorFuturo.setBounds(150, 130, 100, 27);
        jDesktopPane1.add(valorFuturo, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jButton1.setBounds(110, 180, 80, 30);
        jDesktopPane1.add(jButton1, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jLabel7.setText(resourceMap.getString("jLabel7.text")); // NOI18N
        jLabel7.setName("jLabel7"); // NOI18N
        jLabel7.setBounds(220, 50, 20, 17);
        jDesktopPane1.add(jLabel7, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jLabel9.setText(resourceMap.getString("jLabel9.text")); // NOI18N
        jLabel9.setName("jLabel9"); // NOI18N
        jLabel9.setBounds(220, 80, 43, 17);
        jDesktopPane1.add(jLabel9, javax.swing.JLayeredPane.DEFAULT_LAYER);

        rentabilidade.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0.00"))));
        rentabilidade.setName("rentabilidade"); // NOI18N
        rentabilidade.setBounds(150, 40, 60, 27);
        jDesktopPane1.add(rentabilidade, javax.swing.JLayeredPane.DEFAULT_LAYER);

        tempoAplicacao.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0"))));
        tempoAplicacao.setName("tempoAplicacao"); // NOI18N
        tempoAplicacao.setBounds(150, 70, 60, 27);
        jDesktopPane1.add(tempoAplicacao, javax.swing.JLayeredPane.DEFAULT_LAYER);

        capitalInicial.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#,##0.00"))));
        capitalInicial.setName("capitalInicial"); // NOI18N
        capitalInicial.setBounds(150, 10, 90, 27);
        jDesktopPane1.add(capitalInicial, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jButton2.setText(resourceMap.getString("jButton2.text")); // NOI18N
        jButton2.setName("jButton2"); // NOI18N
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jButton2.setBounds(210, 180, 80, 30);
        jDesktopPane1.add(jButton2, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jTabbedPane1.addTab(resourceMap.getString("jDesktopPane1.TabConstraints.tabTitle"), jDesktopPane1); // NOI18N

        jDesktopPane2.setBackground(resourceMap.getColor("jDesktopPane2.background")); // NOI18N
        jDesktopPane2.setName("jDesktopPane2"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        tabela.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Capital Inicial", "Rentabilidade", "Prazo", "Reforço Mensal", "Valor Futuro"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tabela.setColumnSelectionAllowed(true);
        tabela.setName("tabela"); // NOI18N
        jScrollPane1.setViewportView(tabela);
        tabela.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        tabela.getColumnModel().getColumn(0).setHeaderValue(resourceMap.getString("tabela.columnModel.title0")); // NOI18N
        tabela.getColumnModel().getColumn(1).setHeaderValue(resourceMap.getString("tabela.columnModel.title1")); // NOI18N
        tabela.getColumnModel().getColumn(2).setHeaderValue(resourceMap.getString("tabela.columnModel.title2")); // NOI18N
        tabela.getColumnModel().getColumn(3).setHeaderValue(resourceMap.getString("tabela.columnModel.title3")); // NOI18N
        tabela.getColumnModel().getColumn(4).setHeaderValue(resourceMap.getString("tabela.columnModel.title4")); // NOI18N

        jScrollPane1.setBounds(0, 30, 550, 230);
        jDesktopPane2.add(jScrollPane1, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jButton3.setText(resourceMap.getString("jButton3.text")); // NOI18N
        jButton3.setName("jButton3"); // NOI18N
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
        jButton3.setBounds(390, 280, 130, 29);
        jDesktopPane2.add(jButton3, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jLabel5.setText(resourceMap.getString("jLabel5.text")); // NOI18N
        jLabel5.setName("jLabel5"); // NOI18N
        jLabel5.setBounds(10, 290, 530, 17);
        jDesktopPane2.add(jLabel5, javax.swing.JLayeredPane.DEFAULT_LAYER);

        pesoValorFuturo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1", "2", "3", "4", "5" }));
        pesoValorFuturo.setName("pesoValorFuturo"); // NOI18N
        pesoValorFuturo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pesoValorFuturoActionPerformed(evt);
            }
        });
        pesoValorFuturo.setBounds(440, 0, 110, 27);
        jDesktopPane2.add(pesoValorFuturo, javax.swing.JLayeredPane.DEFAULT_LAYER);

        pesoCapitalInicial.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1", "2", "3", "4", "5" }));
        pesoCapitalInicial.setName("pesoCapitalInicial"); // NOI18N
        pesoCapitalInicial.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pesoCapitalInicialActionPerformed(evt);
            }
        });
        pesoCapitalInicial.setBounds(0, 0, 110, 27);
        jDesktopPane2.add(pesoCapitalInicial, javax.swing.JLayeredPane.DEFAULT_LAYER);

        pesoRentabilidade.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1", "2", "3", "4", "5" }));
        pesoRentabilidade.setName("pesoRentabilidade"); // NOI18N
        pesoRentabilidade.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pesoRentabilidadeActionPerformed(evt);
            }
        });
        pesoRentabilidade.setBounds(110, 0, 110, 27);
        jDesktopPane2.add(pesoRentabilidade, javax.swing.JLayeredPane.DEFAULT_LAYER);

        pesoPrazo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1", "2", "3", "4", "5" }));
        pesoPrazo.setName("pesoPrazo"); // NOI18N
        pesoPrazo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pesoPrazoActionPerformed(evt);
            }
        });
        pesoPrazo.setBounds(220, 0, 110, 27);
        jDesktopPane2.add(pesoPrazo, javax.swing.JLayeredPane.DEFAULT_LAYER);

        pesoReforcoMensal.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1", "2", "3", "4", "5" }));
        pesoReforcoMensal.setName("pesoReforcoMensal"); // NOI18N
        pesoReforcoMensal.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pesoReforcoMensalActionPerformed(evt);
            }
        });
        pesoReforcoMensal.setBounds(330, 0, 110, 27);
        jDesktopPane2.add(pesoReforcoMensal, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jTabbedPane1.addTab(resourceMap.getString("jDesktopPane2.TabConstraints.tabTitle"), jDesktopPane2); // NOI18N

        org.jdesktop.layout.GroupLayout mainPanelLayout = new org.jdesktop.layout.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jTabbedPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 558, Short.MAX_VALUE)
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jTabbedPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 362, Short.MAX_VALUE)
        );

        menuBar.setName("menuBar"); // NOI18N

        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(sadfinanceiro.SADFinanceiroApp.class).getContext().getActionMap(SADFinanceiroView.class, this);
        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setText(resourceMap.getString("exitMenuItem.text")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        indicesMenu.setText(resourceMap.getString("indicesMenu.text")); // NOI18N
        indicesMenu.setName("indicesMenu"); // NOI18N
        indicesMenu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                poupancaActionPerformed(evt);
            }
        });

        jMenuItem1.setAction(actionMap.get("showIndicesPoupanca")); // NOI18N
        jMenuItem1.setText(resourceMap.getString("jMenuItem1.text")); // NOI18N
        jMenuItem1.setName("jMenuItem1"); // NOI18N
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        indicesMenu.add(jMenuItem1);

        jMenuItem2.setAction(actionMap.get("showIndicesCDB")); // NOI18N
        jMenuItem2.setText(resourceMap.getString("jMenuItem2.text")); // NOI18N
        jMenuItem2.setName("jMenuItem2"); // NOI18N
        indicesMenu.add(jMenuItem2);

        jMenuItem3.setText(resourceMap.getString("jMenuItem3.text")); // NOI18N
        jMenuItem3.setName("jMenuItem3"); // NOI18N
        indicesMenu.add(jMenuItem3);

        menuBar.add(indicesMenu);

        jMenu1.setText(resourceMap.getString("jMenu1.text")); // NOI18N
        jMenu1.setName("jMenu1"); // NOI18N

        jMenuItem4.setAction(actionMap.get("showHistoricoBox")); // NOI18N
        jMenuItem4.setText(resourceMap.getString("jMenuItem4.text")); // NOI18N
        jMenuItem4.setName("jMenuItem4"); // NOI18N
        jMenu1.add(jMenuItem4);

        jMenuItem5.setAction(actionMap.get("limparHistorico")); // NOI18N
        jMenuItem5.setText(resourceMap.getString("jMenuItem5.text")); // NOI18N
        jMenuItem5.setName("jMenuItem5"); // NOI18N
        jMenu1.add(jMenuItem5);

        menuBar.add(jMenu1);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setText(resourceMap.getString("aboutMenuItem.text")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        setComponent(mainPanel);
        setMenuBar(menuBar);
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        Investimento investimento = new Investimento();
        if (this.capitalInicial.getValue()!=null) {
            investimento.setCapitalInicial(new BigDecimal(this.capitalInicial.getValue().toString()));
        }
        if (this.rentabilidade.getValue()!=null) {
            investimento.setRentabilidade(new BigDecimal(this.rentabilidade.getValue().toString()));
        }
        if (this.tempoAplicacao.getValue()!=null) {
            investimento.setPeriodoAplicacao(((Long)this.tempoAplicacao.getValue()).intValue());
        }
        if (this.valorReforcos.getValue()!=null) {
            investimento.setValorReforco(new BigDecimal(this.valorReforcos.getValue().toString()));
        }
        if (this.valorFuturo.getValue()!=null) {
            investimento.setValorFuturo(new BigDecimal(this.valorFuturo.getValue().toString()));
        }
       try {
           
           //efetua os calculos
           Calculador.calcula(investimento);
 
           //Após efetuar o calculo seta os valores
           this.valorFuturo.setValue(investimento.getValorFuturo());
           this.capitalInicial.setValue(investimento.getCapitalInicial());
           this.rentabilidade.setValue(investimento.getRentabilidade());
           this.valorReforcos.setValue(investimento.getValorReforco());
           this.tempoAplicacao.setValue(investimento.getPeriodoAplicacao());
           
           //seta o cenario na tabela da outra aba
           DefaultTableModel modeloTabela = (DefaultTableModel)tabela.getModel();  
           modeloTabela.addRow(new String[] { this.capitalInicial.getText(), 
                                              this.rentabilidade.getText(), 
                                              this.tempoAplicacao.getText(), 
                                              this.valorReforcos.getText(), 
                                              this.valorFuturo.getText()
                                            }
                              );

           // inclui na tabela de cenarios
            EntityTransaction et = entityManager.getTransaction();
            et.begin();
            entityManager.persist(investimento.toCenario());
            et.commit();

       }catch (Exception e) {
           JOptionPane.showMessageDialog(jDesktopPane1, "Erro: "+e.getMessage());
           e.printStackTrace();
       }
       
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
    }//GEN-LAST:event_jMenuItem1ActionPerformed

    private void poupancaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_poupancaActionPerformed
        jMenuItem1.setVisible(true);
    }//GEN-LAST:event_poupancaActionPerformed

private void valorFuturoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_valorFuturoFocusLost
// TODO add your handling code here:
}//GEN-LAST:event_valorFuturoFocusLost

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    this.valorFuturo.setValue(null);
    this.capitalInicial.setValue(null);
    this.rentabilidade.setValue(null);
    this.valorReforcos.setValue(null);
    this.tempoAplicacao.setValue(null);
}//GEN-LAST:event_jButton2ActionPerformed

/*
 * Função para normalizar os dados
 * Utiliza o metodo Decima Scaling
 * Mais detalhes: http://books.google.com.br/books?id=AfL0t-YzOrEC&printsec=frontcover&dq=Data+Mining:+Concepts+and+Techniques&lr=#PPA71,M1
 * 
 */
private Float normalizar(Float valor, int colunaTabela) {

    //percorre todos os campos da coluna para pegar o maior e ver por quanto tem que dividir para normalizar
    Float maior = 0f;
    for (int i=0; i < tabela.getRowCount(); i++) {
        
        try {
            Float valorColuna = new Float(df.parse((String) tabela.getValueAt(i, colunaTabela)).floatValue());
            if (valorColuna.floatValue() > maior.floatValue()) {
                maior = valorColuna;
            }
        } catch (ParseException ex) {
            Logger.getLogger(SADFinanceiroView.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    Float divisor = 1f;
    
    while (maior > 1) {
           
        maior = maior / 10;
        divisor = divisor * 10;
    }
    
    valor = valor/divisor;

    System.out.println(valor);
    
    return (valor);
    
}


private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
    
       // row keys...
        String series1 = "Capital Inicial";
        String series2 = "Rentabilidade";
        String series3 = "Prazo";
        String series4 = "Reforço";
        String series5 = "Valor Futuro";
      

        // create the dataset...
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    
        //percorre as linhas dos cenarios e cria o grafico
        if (tabela.getRowCount() > 0) {
            
            for (int i=0; i < tabela.getRowCount(); i++) {
            
                try {
                    
                    Float capitalInicial = new Float(df.parse((String) tabela.getValueAt(i, 0)).floatValue());
                    Float rentabilidade = new Float(df.parse((String)tabela.getValueAt(i, 1)).floatValue());
                    Float prazo = new Float(df.parse((String)tabela.getValueAt(i, 2)).floatValue());
                    Float reforço = new Float(df.parse((String)tabela.getValueAt(i, 3)).floatValue());
                    Float valorFuturo = new Float(df.parse((String)tabela.getValueAt(i, 4)).floatValue());
                
                    dataset.addValue(normalizar(capitalInicial,0), series1, "Cenário " + (i+1));
                
                    dataset.addValue(normalizar(rentabilidade,1), series2, "Cenário " + (i+1));

                    dataset.addValue(normalizar(prazo,2), series3, "Cenário " + (i+1));

                    dataset.addValue(normalizar(reforço,3), series4, "Cenário " + (i+1));

                    dataset.addValue(normalizar(valorFuturo,4), series5, "Cenário " + (i+1));

                } catch (ParseException ex) {
                    Logger.getLogger(SADFinanceiroView.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

            SADFinanceiroGraficoView demo = new SADFinanceiroGraficoView(dataset);
            demo.pack();
            RefineryUtilities.centerFrameOnScreen(demo);
            demo.setVisible(true);

        }
        
        
}//GEN-LAST:event_jButton3ActionPerformed


private void reordenaTabela() {
        //percorre as linhas dos cenarios e cria o grafico
        if (tabela.getRowCount() > 0) {
            
            //cria uma lista com todos as linhas da tabela
            ArrayList<SADFinanceiroVOTabela> lista = new ArrayList();
            
            for (int i=0; i < tabela.getRowCount(); i++) {
            
                try {
                    
                    Float capitalInicial = new Float(df.parse((String) tabela.getValueAt(i, 0)).floatValue());
                    Float rentabilidade = new Float(df.parse((String)tabela.getValueAt(i, 1)).floatValue());
                    Float prazo = new Float(df.parse((String)tabela.getValueAt(i, 2)).floatValue());
                    Float reforço = new Float(df.parse((String)tabela.getValueAt(i, 3)).floatValue());
                    Float valorFuturo = new Float(df.parse((String)tabela.getValueAt(i, 4)).floatValue());
                    
                    SADFinanceiroVOTabela vo = new SADFinanceiroVOTabela();
                    vo.setCapitalInicial(capitalInicial);
                    vo.setRentabilidade(rentabilidade);
                    vo.setPrazo(prazo);
                    vo.setReforço(reforço);
                    vo.setValorFuturo(valorFuturo);
                    
                    lista.add(vo);
                            
                    
                } catch (ParseException ex) {
                    Logger.getLogger(SADFinanceiroView.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            
            //ordena de acordo com os pesos especificados            
            final int pCapitalInicial = new Integer(pesoCapitalInicial.getSelectedItem().toString());
            final int pRentabilidade = new Integer(pesoRentabilidade.getSelectedItem().toString());
            final int pPrazo = new Integer(pesoPrazo.getSelectedItem().toString());
            final int pReforço = new Integer(pesoReforcoMensal.getSelectedItem().toString());
            final int pValorFuturo = new Integer(pesoValorFuturo.getSelectedItem().toString());
            
            Collections.sort(lista,new Comparator() {
                public int compare(Object obj, Object obj1) {

                    int result1 = 0;
                    int result2 = 0;
                    int result3 = 0;
                    int result4 = 0;
                    int result5 = 0;

                    //result 5
                    if (pCapitalInicial == 5) {
                        result5 = ((SADFinanceiroVOTabela) obj1).getCapitalInicial().compareTo( ((SADFinanceiroVOTabela) obj).getCapitalInicial() );
                    }
                    if (pRentabilidade == 5) {
                        result5 = ((SADFinanceiroVOTabela) obj1).getRentabilidade().compareTo( ((SADFinanceiroVOTabela) obj).getRentabilidade() );
                    }
                    if (pPrazo == 5) {
                        result5 = ((SADFinanceiroVOTabela) obj1).getPrazo().compareTo( ((SADFinanceiroVOTabela) obj).getPrazo() );
                    }
                    if (pReforço == 5) {
                        result5 = ((SADFinanceiroVOTabela) obj1).getReforço().compareTo( ((SADFinanceiroVOTabela) obj).getReforço() );
                    }
                    if (pValorFuturo == 5) {
                        result5 = ((SADFinanceiroVOTabela) obj1).getValorFuturo().compareTo( ((SADFinanceiroVOTabela) obj).getValorFuturo() );
                    }

                    //result 4
                    if (pCapitalInicial == 4) {
                        result4 = ((SADFinanceiroVOTabela) obj1).getCapitalInicial().compareTo( ((SADFinanceiroVOTabela) obj).getCapitalInicial() );
                    }
                    if (pRentabilidade == 4) {
                        result4 = ((SADFinanceiroVOTabela) obj1).getRentabilidade().compareTo( ((SADFinanceiroVOTabela) obj).getRentabilidade() );
                    }
                    if (pPrazo == 4) {
                        result4 = ((SADFinanceiroVOTabela) obj1).getPrazo().compareTo( ((SADFinanceiroVOTabela) obj).getPrazo() );
                    }
                    if (pReforço == 4) {
                        result4 = ((SADFinanceiroVOTabela) obj1).getReforço().compareTo( ((SADFinanceiroVOTabela) obj).getReforço() );
                    }
                    if (pValorFuturo == 4) {
                        result4 = ((SADFinanceiroVOTabela) obj1).getValorFuturo().compareTo( ((SADFinanceiroVOTabela) obj).getValorFuturo() );
                    }

                    //result 3
                    if (pCapitalInicial == 3) {
                        result3 = ((SADFinanceiroVOTabela) obj1).getCapitalInicial().compareTo( ((SADFinanceiroVOTabela) obj).getCapitalInicial() );
                    }
                    if (pRentabilidade == 3) {
                        result3 = ((SADFinanceiroVOTabela) obj1).getRentabilidade().compareTo( ((SADFinanceiroVOTabela) obj).getRentabilidade() );
                    }
                    if (pPrazo == 3) {
                        result3 = ((SADFinanceiroVOTabela) obj1).getPrazo().compareTo( ((SADFinanceiroVOTabela) obj).getPrazo() );
                    }
                    if (pReforço == 3) {
                        result3 = ((SADFinanceiroVOTabela) obj1).getReforço().compareTo( ((SADFinanceiroVOTabela) obj).getReforço() );
                    }
                    if (pValorFuturo == 3) {
                        result3 = ((SADFinanceiroVOTabela) obj1).getValorFuturo().compareTo( ((SADFinanceiroVOTabela) obj).getValorFuturo() );
                    }

                    //result 2
                    if (pCapitalInicial == 2) {
                        result2 = ((SADFinanceiroVOTabela) obj1).getCapitalInicial().compareTo( ((SADFinanceiroVOTabela) obj).getCapitalInicial() );
                    }
                    if (pRentabilidade == 2) {
                        result2 = ((SADFinanceiroVOTabela) obj1).getRentabilidade().compareTo( ((SADFinanceiroVOTabela) obj).getRentabilidade() );
                    }
                    if (pPrazo == 2) {
                        result2 = ((SADFinanceiroVOTabela) obj1).getPrazo().compareTo( ((SADFinanceiroVOTabela) obj).getPrazo() );
                    }
                    if (pReforço == 2) {
                        result2 = ((SADFinanceiroVOTabela) obj1).getReforço().compareTo( ((SADFinanceiroVOTabela) obj).getReforço() );
                    }
                    if (pValorFuturo == 2) {
                        result2 = ((SADFinanceiroVOTabela) obj1).getValorFuturo().compareTo( ((SADFinanceiroVOTabela) obj).getValorFuturo() );
                    }

                    //result 1
                    if (pCapitalInicial == 1) {
                        result1 = ((SADFinanceiroVOTabela) obj1).getCapitalInicial().compareTo( ((SADFinanceiroVOTabela) obj).getCapitalInicial() );
                    }
                    if (pRentabilidade == 1) {
                        result1 = ((SADFinanceiroVOTabela) obj1).getRentabilidade().compareTo( ((SADFinanceiroVOTabela) obj).getRentabilidade() );
                    }
                    if (pPrazo == 1) {
                        result1 = ((SADFinanceiroVOTabela) obj1).getPrazo().compareTo( ((SADFinanceiroVOTabela) obj).getPrazo() );
                    }
                    if (pReforço == 1) {
                        result1 = ((SADFinanceiroVOTabela) obj1).getReforço().compareTo( ((SADFinanceiroVOTabela) obj).getReforço() );
                    }
                    if (pValorFuturo == 1) {
                        result1 = ((SADFinanceiroVOTabela) obj1).getValorFuturo().compareTo( ((SADFinanceiroVOTabela) obj).getValorFuturo() );
                    }

                    if (result5 == 0) {
                        if (result4 == 0) {
                            if (result3 == 0) {
                                if (result2 == 0) {
                                    return result1;
                                } else {
                                    return result2;
                                }
                            } else {
                                return result3;
                            }
                        } else {
                            return result4;
                        }
                    } else {
                        return result5;
                    }
                }
            });
                    
            
            //limpa a tabela e adiciona novamente os itens ordenados
            DefaultTableModel tableModel =(DefaultTableModel) tabela.getModel();  
            tableModel.setNumRows(0);  
            
            for (SADFinanceiroVOTabela vo : lista) {
            
                 DefaultTableModel modeloTabela = (DefaultTableModel)tabela.getModel();  
                 modeloTabela.addRow(new String[] { df.format(vo.getCapitalInicial()), 
                                              df.format(vo.getRentabilidade()), 
                                              df.format(vo.getPrazo()), 
                                              df.format(vo.getReforço()), 
                                              df.format(vo.getValorFuturo())
                                            }
                              );
            }
            
        }
}


private void pesoCapitalInicialActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pesoCapitalInicialActionPerformed
    reordenaTabela();
}//GEN-LAST:event_pesoCapitalInicialActionPerformed

private void pesoRentabilidadeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pesoRentabilidadeActionPerformed
    reordenaTabela();
}//GEN-LAST:event_pesoRentabilidadeActionPerformed

private void pesoPrazoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pesoPrazoActionPerformed
    reordenaTabela();
}//GEN-LAST:event_pesoPrazoActionPerformed

private void pesoReforcoMensalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pesoReforcoMensalActionPerformed
    reordenaTabela();
}//GEN-LAST:event_pesoReforcoMensalActionPerformed

private void pesoValorFuturoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pesoValorFuturoActionPerformed
    reordenaTabela();
}//GEN-LAST:event_pesoValorFuturoActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JFormattedTextField capitalInicial;
    private javax.persistence.EntityManager entityManager;
    private javax.swing.JMenu indicesMenu;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JDesktopPane jDesktopPane1;
    private javax.swing.JDesktopPane jDesktopPane2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JMenuItem jMenuItem4;
    private javax.swing.JMenuItem jMenuItem5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JComboBox pesoCapitalInicial;
    private javax.swing.JComboBox pesoPrazo;
    private javax.swing.JComboBox pesoReforcoMensal;
    private javax.swing.JComboBox pesoRentabilidade;
    private javax.swing.JComboBox pesoValorFuturo;
    private javax.swing.JFormattedTextField rentabilidade;
    private javax.swing.JTable tabela;
    private javax.swing.JFormattedTextField tempoAplicacao;
    private javax.swing.JFormattedTextField valorFuturo;
    private javax.swing.JFormattedTextField valorReforcos;
    // End of variables declaration//GEN-END:variables

    private JDialog aboutBox;
    private JDialog indicesView;
    private JDialog historicoView;
}
